<template>
  <div class='app-container calendar-list-container'>
    <div class='filter-container'>
      <el-input @keyup.enter.native='handleFilter' style='width: 200px;' class='filter-item' placeholder='食品名' v-model='listQuery.descr'>
      </el-input>
      <el-select v-model="listQuery.restId" placeholder="选择食堂">
        <el-option
          v-for="item in rests"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-button class='filter-item' type='primary' v-waves icon='search' @click='handleFilter'>搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="edit">添加</el-button>
      <el-button class="filter-item" type="primary" icon="document" @click="handleDownload">导出</el-button>
      <el-button class='filter-item' type='primary' :disabled="this.sels.length === 0" v-waves icon='delete' @click='handleDel'>删除</el-button>
      <el-checkbox class="filter-item" @change='tableKey=tableKey+1' v-model="showAuditor">显示详细</el-checkbox>
    </div>
    <el-table height="400" @selection-change="selsChange" :key='tableKey' :data='list' v-loading='listLoading' element-loading-text='给我一点时间' border fit highlight-current-row style='width: 100%'>

      <el-table-column type="selection">
      </el-table-column>
      <el-table-column   type="index" width="60">
      </el-table-column>

      <el-table-column  label='名称' prop="descr" width="150">
      </el-table-column>
      <el-table-column label='描述' show-overflow-tooltip width="200" prop="longDescr">
      </el-table-column>
      <el-table-column label='类别'>
        <template scope="scope">
          {{scope.row.kindDescr}}
        </template>
      </el-table-column>
      <el-table-column label='食堂' show-overflow-tooltip width="200" prop="restDescr">
      </el-table-column>
      <el-table-column v-if='showAuditor' align="center" label="价格" prop="price">
      </el-table-column>
      <el-table-column v-if='showAuditor' align="center" label="包装费" prop="package">
      </el-table-column>
      <el-table-column v-if='showAuditor' align="center" label="午餐售卖">
        <template scope="scope">
          <el-tag size="medium" :type="scope.row.ifLunch === '1' ? 'success' : 'error'">{{scope.row.ifLunch | ifFilter}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if='showAuditor' align="center" label="晚餐售卖">
        <template scope="scope">
          <el-tag size="medium" :type="scope.row.ifDinner === '1' ? 'success' : 'error'">{{scope.row.ifDinner | ifFilter}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if='showAuditor' align="center" label="月售数" prop="monthSelNum">
      </el-table-column>
      <el-table-column label='状态' align="center" width="100">
        <template scope="scope">
          <el-tag size="medium" :type="scope.row.enable === '1' ? 'success' : 'error'">{{scope.row.enable | enableFilter}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="150">
        <template scope="scope">
          <el-button size="small" type="success" @click="handleUpdate(scope.row)">修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show='!listLoading' class='pagination-container'>
      <el-pagination @size-change='handleSizeChange' @current-change='handleCurrentChange' :current-page.sync='listQuery.page'
        :page-sizes='[10,20,30,50]' :page-size='listQuery.limit' layout='total, sizes, prev, pager, next, jumper' :total='total'>
      </el-pagination>
    </div>

    <el-dialog :title="textMap[0]" :visible.sync="dialogFormVisible">
      <el-form class="small-space" :model="temp" :rules="rules" ref="form" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="名称" prop="descr">
          <el-input v-model="temp.descr"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="temp.longDescr"></el-input>
        </el-form-item>
        <el-form-item label="种类">
          <el-select v-model="restKindsSel" multiple>
            <el-option
              v-for="item in restKinds"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格">
          <el-input-number :min="0" v-model="temp.price"></el-input-number>
        </el-form-item>
        <el-form-item label="包装费">
          <el-input-number :min="0" v-model="temp.package"></el-input-number>
        </el-form-item>
        
        <el-form-item label="午餐售卖">
          <el-radio v-model="temp.ifLunch" label="1">是</el-radio>
          <el-radio v-model="temp.ifLunch" label="0">否</el-radio>
        </el-form-item>
        <el-form-item label="晚餐售卖">
          <el-radio v-model="temp.ifDinner" label="1">是</el-radio>
          <el-radio v-model="temp.ifDinner" label="0">否</el-radio>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="temp.enable">
            <el-option label="生效" value="1"></el-option>
            <el-option label="无效" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="update">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList,create,update,del } from '@/api/food';
import { restSel,restKindsSel } from '@/api/rest';
import waves from '@/directive/waves/index.js'; // 水波纹指令

export default {
  name: 'x',
  directives: {
    waves
  },
  data() {
    return {
      restKinds: [],
      rests: [],
      restKindsSel:[],
      sels: [],
      list: null,
      showAuditor: false,
      total: null,
      listLoading: null,
      listQuery: {
        page: 1,
        limit: 20,
        restId: undefined,
        descr: undefined,
        sort: '+fd.id'
      },
      ifOptions: [{
          value: '0',
          label: '否'
        }, {
          value: '1',
          label: '是'
        }
      ],
      temp : {
        id: undefined,
        descr: '',
        longDescr: '',
        price: 0,
        package: 0,
        ifDinner: '',
        ifLunch: '',
        kindId: '',
        kindDescr: '',
        enable: ''
      },
      delids : {
        ids : ''
      },
      textMap: {
        update: '编辑',
        create: '创建'
      },
      dialogFormVisible: false,
      tableKey: 0,
      restaurant_id:'',
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getRests();
  },
  filters: {
    enableFilter: function (value) {
      if('1'===value){
        return "有效"
      }
      return "无效"
    },
    ifFilter: function (value) {
      if('1'===value){
        return "是"
      }
      return "否"
    }
  },
  methods: {
    getList() {
      this.listLoading = true;
      fetchList(this.listQuery).then(response => {
        // debugger
        this.list = response.data.items;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    getRests() {
      restSel().then(response => {
        // debugger
        this.rests = response.data.items;
      });
    },
    async getRestKinds(){
      try{
        const result = await restKindsSel(this.restaurant_id);
        if(result.data.code=1){
          this.restKinds=result.data.items
        }else{
          console.log(result)
        }
      }catch(err){
        console.log(err)
      }
    },
    handleCreate() {
      this.$msgbox({
        title: '提示',
        message: '添加食品需要选择一个商铺，先去就去选择商铺吗？',
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            this.$router.push('/sets/restaurant');
            done();
          } else {
            this.$message({
              type: 'info',
              message: '取消'
          });
              done();
          }
        }
      })
    },
    handleUpdate(row) {
      this.restaurant_id=row.restId;
      this.getRestKinds();
      this.temp = Object.assign({}, row)
      if(row.kindId && row.kindId!=''){
        this.restKindsSel=row.kindId.split(',')
      }
      this.dialogFormVisible = true
    },
    selsChange(sels) {  
      this.sels = sels  
    }, 
    handleDel() {
      this.$confirm('删除?', '提示', { type: 'warning' }) 
        .then(async () => { 
          const idg = this.sels.map(item => item.id)
          console.log(idg)
          this.delids.ids = this.sels.map(item => item.id).join()
          const res = await del(this.delids)
          // debugger
          if(res.data.code==1){
            for (const y of idg) {
              for (const v of this.list) {
                if (v.id === y) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1)
                  break
                }
              }
            }
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          }else{
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000
            })
          }
        }
        ).catch(() => {
          this.$notify({
            title: '失败',
            message: '删除失败',
            type: 'error',
            duration: 2000
          })
        })
    },
    update() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          const kindDescrArray=[]
          for(const v of this.restKindsSel){
            for(const y of this.restKinds){
              if(v===y.value){
                kindDescrArray.push(y.label)
              }
            }
          }
          this.temp.kindDescr = kindDescrArray.join(',')
          this.temp.kindId = this.restKindsSel.join(',')
          const res = await update(this.temp)
          if(res.data.code==1){
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          }else{
            this.$notify({
              title: '失败',
              message: '更新失败',
              type: 'error',
              duration: 2000
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
        this.dialogFormVisible = false
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        descr: ''
      }
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleDownload() {
      require.ensure([], () => {
        const { export_json_to_excel } = require('vendor/Export2Excel')
        const tHeader = ['ID', '名称', '描述', '地址', '电话']
        const filterVal = ['id', 'descr', 'longDescr', 'location', 'tel']
        const data = this.formatJson(filterVal, this.list)
        export_json_to_excel(tHeader, data, 'table数据')
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'tel') {
          return '不可下载'
        } else {
          return v[j]
        }
      }))
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    }
  }
};
</script>